type ResourceMetric = {
    name: string
    duration: number
    initiatorType?: string
    size?: number
    transferSize?: number // 实际传输大小
    protocol?: string // 协议类型
}

export function trackResourceTiming(report: (data: ResourceMetric) => void) {
    if (typeof window === "undefined" || !("Performance" in window)) return

    // 监听所有资源加载
    const observer = new PerformanceObserver(list => {
        list.getEntries().forEach(entry => {
            // 类型断言为 PerformanceResourceTiming
            const resourceEntry = entry as PerformanceResourceTiming

            const metric: ResourceMetric = {
                name: resourceEntry.name,
                duration: resourceEntry.duration
            }
            // 仅当属性存在时添加
            if ("initiatorType" in resourceEntry) {
                metric.initiatorType = resourceEntry.initiatorType
            }
            if ("decodedBodySize" in resourceEntry) {
                metric.size = resourceEntry.decodedBodySize
            }
            if ("transferSize" in resourceEntry) {
                metric.transferSize = resourceEntry.transferSize
            }
            if ("nextHopProtocol" in resourceEntry) {
                metric.protocol = resourceEntry.nextHopProtocol
            }

            report(metric)
        })
    })
    observer.observe({ type: "resource", buffered: true })
}
